package cn.usts.edu.lesson03;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/**
 * 使用callable接口
 * 1.创建执行服务
 * 2.提交执行服务
 * 3.获取执行结果
 * 4.关闭服务
 * */

public class CallableDemo implements Callable {
    String file;
    String url;
    String filename;

    public CallableDemo(String file, String url) {
        this.file = file;
        this.url = url;
    }

    @Override
    public Boolean call() {
        ImageDownload imageDownload = new ImageDownload();
        imageDownload.downLoad(url,file);
        filename = file.split("\\\\")[11];//获取文件名
        System.out.println(filename+"下载完成");
        return true;
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CallableDemo t1 = new CallableDemo(
                "D:\\all_projects\\java_projects\\java_ij\\springMVC\\ThreadStudy\\src\\cn\\usts\\edu\\lesson01\\a.jpg"
                ,"https://bbs.qn.img-space.com/202110/18/1c3eb5a6f1d59adaa9b608c7da64d95a.jpg");
        CallableDemo t2 = new CallableDemo(
                "D:\\all_projects\\java_projects\\java_ij\\springMVC\\ThreadStudy\\src\\cn\\usts\\edu\\lesson01\\b.jpg"
                ,"https://bbs.qn.img-space.com/202110/18/6d254e56adf9094cc003c815d3d6d3e1.jpg");
        CallableDemo t3 = new CallableDemo(
                "D:\\all_projects\\java_projects\\java_ij\\springMVC\\ThreadStudy\\src\\cn\\usts\\edu\\lesson01\\c.jpg"
                ,"https://bbs.qn.img-space.com/202110/18/72d862d6074bb2edc1e6df61ce78455f.jpg"
        );

        //        *1.创建执行服务
        ExecutorService service = Executors.newFixedThreadPool(3);

        //        * 2.提交执行服务
        Future<Boolean> r1 = service.submit(t1);
        Future<Boolean> r2 = service.submit(t2);
        Future<Boolean> r3 = service.submit(t3);

        //        * 3.获取执行结果
        boolean rs1 = r1.get();
        boolean rs2 = r2.get();
        boolean rs3 = r3.get();
        System.out.println(rs1);
        System.out.println(rs2);
        System.out.println(rs3);

        //        * 4.关闭服务
        service.shutdown();

    }

}

class  ImageDownload{

    public void downLoad(String url,String file)  {
        try {
            FileUtils.copyURLToFile(new URL(url),new File(file));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("downLoad()方法出错");
        }
    }
}